package cn.javasea.websocket.utils;

import cn.javasea.websocket.entity.JsonMessage;
import cn.javasea.websocket.entity.Notice;
import cn.javasea.websocket.websocket.LoginUserCache;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.util.List;

/**
 * @author: 97622
 * @description: websocket通讯广播工具
 * @date: 2020/7/14 10:09
 * @version: 1.0
 **/
@Slf4j
public class WsBroadcastUtil {


    /**
     * 按userIds查找sessionMap的session，然后发布通知
     *
     * @param userIds 接收者
     * @param msg     消息-json
     */
    public static void broadcastNotifications(List<String> userIds, JsonMessage msg) {
        userIds.stream().parallel().forEach(item -> {
//            log.info("发送消息：" + item + "；msg：" + msg);
            Session session = LoginUserCache.get(item).getSession();
            if (null != session && session.isOpen()) {
                session.getAsyncRemote().sendText(JacksonUtils.obj2json(msg));
            }
        });
    }

    public static void broadcastNotifications(List<String> userIds, Notice notice) {
        userIds.stream().parallel().forEach(item -> {
            Session session = LoginUserCache.get(item).getSession();
            if (null != session && session.isOpen()) {
                session.getAsyncRemote().sendText(JacksonUtils.obj2json(notice));
            }
        });
    }

    public static void broadcastNotifications(String userId, JsonMessage msg) {
        Session session = LoginUserCache.get(userId).getSession();
        if (null != session && session.isOpen()) {
            session.getAsyncRemote().sendText(JacksonUtils.obj2json(msg));
        }
    }

    public static void broadcastNotifications(String userId, String msg) {
        Session session = LoginUserCache.get(userId).getSession();
        if (null != session && session.isOpen()) {
            session.getAsyncRemote().sendText(msg);
        }
    }

    public static void broadcastNotifications(Session session, JsonMessage msg) {
        if (session.isOpen()) {
            session.getAsyncRemote().sendText(JacksonUtils.obj2json(msg));
        } else {
            log.error("[{}] is closed", session.getId());
        }
    }
}
